package com.ruoyi.business.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.business.api.DingDingApi;
import com.ruoyi.business.api.KingDeeApi;
import com.ruoyi.business.api.WeighBridgeApi;
import com.ruoyi.business.domain.ReceivingBillentry;
import com.ruoyi.business.domain.ReceivingBillentryHand;
import com.ruoyi.business.domain.ReceivingBillentryPound;
import com.ruoyi.business.domain.ReceivingNote;
import com.ruoyi.business.service.ReceivingBillentryHandService;
import com.ruoyi.business.service.ReceivingBillentryPoundService;
import com.ruoyi.business.service.ReceivingBillentryService;
import com.ruoyi.business.service.ReceivingNoteService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 原材料收货通知单Controller
 *
 * @author ruoyi
 * @date 2024-07-30
 */
@RestController
@RequestMapping("/system/receiving")
@Slf4j
public class ReceivingNoteController extends BaseController {
    @Autowired
    WeighBridgeApi weighBridgeApi;

    @Autowired
    private KingDeeApi kingDeeApi;

    @Autowired
    private DingDingApi dingDingApi;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ReceivingNoteService receivingNoteService;

    @Autowired
    private ReceivingBillentryService billentryService;

    @Autowired
    private ReceivingBillentryHandService billentryHandService;

    @Autowired
    private ReceivingBillentryPoundService billentryPoundService;

    /**
     * 查询原材料收货通知单列表
     */
    @PreAuthorize("@ss.hasPermi('system:note:list')")
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request) throws IOException {
        //库管员 100
        //收发货员 101
        List<Long> ids = roleService.selectRoleListByUserId(getUserId());
        startPage();
        QueryWrapper<ReceivingNote> query = Wrappers.query();

        int type = Integer.parseInt(request.getParameter("type"));
        switch (type) {
            case 1:
                if (ids.contains(101L)) {
                    query.eq("status", 1);
                } else {
                    query.in("status", 0, 1);
                }
                break;
            case 2:
                if (ids.contains(100L)) {
                    query.eq("status", 2);
                } else {
                    if (!ids.contains(101L)) {
                        query.in("status", 1, 2);
                    }
                }
                break;
            case 3:
                query.eq("status", 3);
                break;
        }
        String supplySupplier = request.getParameter("supplySupplier");
        if (StringUtils.isNotEmpty(supplySupplier)) {
            query.like("supply_supplier", supplySupplier);
        }
        if (StringUtils.isNotEmpty(request.getParameter("biztime"))) {
            Date biztime = DateUtils.parseDate(request.getParameter("biztime"));
            query.eq("biztime", biztime);
        }
        if (!SysUser.isAdmin(getUserId())) {
            //库管员角色
            SysUser user = new SysUser();
            user.setRoleId(100L);
            ArrayList<String> userListArr = new ArrayList<>();
            ArrayList<String> userListArr1 = new ArrayList<>();
            List<SysUser> userList = userService.selectAllocatedList(user);
            for (SysUser sysUser : userList) {
                userListArr.add(sysUser.getUserId().toString());
            }
            if (userListArr.contains(getUserId())) {
                query.in("uid", userListArr);
            }
            //收发货员角色
            user.setRoleId(101L);
            List<SysUser> userList1 = userService.selectAllocatedList(user);
            for (SysUser sysUser : userList1) {
                userListArr1.add(sysUser.getUserId().toString());
            }
            if (userListArr1.contains(getUserId())) {
                query.in("take_id", userListArr1);
            }
        }
        List<ReceivingNote> list = receivingNoteService.list(query);
        return getDataTable(list);
    }

    /**
     * 导出原材料收货通知单列表
     */
    @PreAuthorize("@ss.hasPermi('system:note:export')")
    @Log(title = "原材料收货通知单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ReceivingNote receivingNote) {
        List<ReceivingNote> list = receivingNoteService.queryList(receivingNote);
        ExcelUtil<ReceivingNote> util = new ExcelUtil<ReceivingNote>(ReceivingNote.class);
        util.exportExcel(response, list, "原材料收货通知单数据");
    }

    /**
     * 获取原材料收货通知单详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:note:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        ReceivingNote note = receivingNoteService.getById(id);
        ReceivingBillentry billentry = new ReceivingBillentry();
        billentry.setReceivingId(id);
        List<ReceivingBillentry> billentryList = billentryService.queryList(billentry);

        ReceivingBillentryHand billentryHand = new ReceivingBillentryHand();
        billentryHand.setReceivingId(id);
        List<ReceivingBillentryHand> billentryHandList = billentryHandService.queryList(billentryHand);

        ReceivingBillentryPound billentryPound = new ReceivingBillentryPound();
        billentryPound.setReceivingId(id);
        List<ReceivingBillentryPound> billentryPoundList = billentryPoundService.queryList(billentryPound);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(note));
        jsonObject.put("receivingInfo", billentryList);
        jsonObject.put("receivingHandInfo", billentryHandList);
        jsonObject.put("receivingPoundInfo", billentryPoundList);
        return success(jsonObject);
    }

    /**
     * 撤销
     *
     * @param id
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author JerryLu
     * @date 2024/9/4 15:04
     */
    @PreAuthorize("@ss.hasPermi('system:note:cancel')")
    @GetMapping(value = "/cancel/{id}")
    public AjaxResult cancel(@PathVariable("id") Long id) {
        ReceivingNote note = receivingNoteService.getById(id);
        if (note.getStatus() >= 2) {
            return error("通知单已确认收货,不支持撤回!");
        }
        note.setId(id);
        note.setStatus(0);
        note.setUpdateTime(DateUtils.getNowDate());
        return success(receivingNoteService.updateById(note));
    }

    /**
     * 新增原材料收货通知单
     *
     * @param json
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author JerryLu
     * @date 2024/9/7 14:58
     */
    @PreAuthorize("@ss.hasPermi('system:note:add')")
    @Log(title = "原材料收货通知单", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping
    public AjaxResult add(@RequestBody JSONObject json) {
        try {
            ReceivingNote receivingNote = JSONObject.parseObject(json.toString(), ReceivingNote.class);
            receivingNote.setUid(getUserId());
            receivingNote.setUname(getLoginUser().getUser().getNickName());
            receivingNote.setCreateTime(DateUtils.getNowDate());
            receivingNote.setStatus(1);
            //收发货人ID
            SysUser user = new SysUser();
            user.setRoleId(101L);
            List<SysUser> userList = userService.selectAllocatedList(user);
            receivingNote.setTakeId(userList.get(0).getUserId());
            receivingNote.setTakeName(userList.get(0).getNickName());
            receivingNote.setBilltype(DictUtils.getDictLabel("sys_receipt_type", receivingNote.getBilltype()));
            receivingNote.setBiztype(DictUtils.getDictLabel("sys_biztype_type", receivingNote.getBiztype()));
            receivingNoteService.save(receivingNote);

            Long id = receivingNote.getId();
            List<ReceivingBillentry> arr = JSON.parseArray(json.getString("form"), ReceivingBillentry.class);
            for (ReceivingBillentry receivingBillentry : arr) {
                ReceivingBillentryHand billentryHand = JSONObject.parseObject(JSON.toJSONString(receivingBillentry), ReceivingBillentryHand.class);
                ReceivingBillentryPound billentryPound = JSONObject.parseObject(JSON.toJSONString(receivingBillentry), ReceivingBillentryPound.class);
                receivingBillentry.setReceivingId(id);
                receivingBillentry.setRawId(receivingBillentry.getRawId());
                receivingBillentry.setReceiptNo(receivingNote.getReceiptNo());
                receivingBillentry.setCreateTime(DateUtils.getNowDate());
                billentryService.save(receivingBillentry);

                billentryHand.setReceivingId(id);
                billentryHand.setRawId(receivingBillentry.getRawId());
                billentryHand.setReceiptNo(receivingNote.getReceiptNo());
                billentryHand.setCreateTime(DateUtils.getNowDate());
                billentryHandService.save(billentryHand);

                billentryPound.setReceivingId(id);
                billentryPound.setRawId(receivingBillentry.getRawId());
                billentryPound.setReceiptNo(receivingNote.getReceiptNo());
                billentryPound.setCreateTime(DateUtils.getNowDate());
                billentryPoundService.save(billentryPound);
            }

            return success();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 修改原材料收货通知单
     *
     * @param json
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author JerryLu
     * @date 2024/9/7 14:58
     */
    @PreAuthorize("@ss.hasPermi('system:note:edit')")
    @Log(title = "原材料收货通知单", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody JSONObject json) {
        //撤回修改完直接更改状态为待确认
        try {
            ReceivingNote receivingNote = JSONObject.parseObject(json.toString(), ReceivingNote.class);
            receivingNote.setStatus(1);
            receivingNote.setUpdateTime(DateUtils.getNowDate());
            receivingNote.setBilltype(DictUtils.getDictLabel("sys_receipt_type", receivingNote.getBilltype()));
            receivingNote.setBiztype(DictUtils.getDictLabel("sys_biztype_type", receivingNote.getBiztype()));
            receivingNoteService.updateById(receivingNote);

            Long id = receivingNote.getId();
            if (json.getString("form") != null) {
                List<ReceivingBillentry> arr = JSON.parseArray(json.getString("form"), ReceivingBillentry.class);
                for (ReceivingBillentry receivingBillentry : arr) {
                    if (receivingBillentry.getId() == null || receivingBillentry.getId() == 0) {
                        receivingBillentry.setReceivingId(id);
                        receivingBillentry.setRawId(receivingBillentry.getRawId());
                        receivingBillentry.setReceiptNo(receivingNote.getReceiptNo());
                        receivingBillentry.setCreateTime(DateUtils.getNowDate());
                        billentryService.save(receivingBillentry);
                    } else {
                        receivingBillentry.setUpdateTime(DateUtils.getNowDate());
                        billentryService.updateById(receivingBillentry);
                    }
                }
            }

            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**
     * 删除原材料收货通知单
     */
    @PreAuthorize("@ss.hasPermi('system:note:remove')")
    @Log(title = "原材料收货通知单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(receivingNoteService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 同步金蝶收料通知单
     *
     * @param jsonObject
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author JerryLu
     * @date 2024/8/21 16:41
     */
    @PostMapping("/sync/receipt_note_info")
    public AjaxResult syncReceivingNoteInfo(@RequestBody JSONObject jsonObject) {
        return kingDeeApi.syncReceivingNoteInfo(jsonObject);
    }

    /**
     * 收发货员完成收货
     *
     * @param json
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author JerryLu
     * @date 2024/9/6 11:49
     */
    @PreAuthorize("@ss.hasPermi('system:note:finish')")
    @PostMapping("/finish_receiving")
    @Transactional
    public AjaxResult finishReceiving(@RequestBody JSONObject json) {
        try {
            ReceivingNote receivingNote = JSONObject.parseObject(json.toString(), ReceivingNote.class);
            receivingNote.setStatus(2);
            receivingNote.setUpdateTime(DateUtils.getNowDate());
            receivingNoteService.updateById(receivingNote);
            if (json.getString("billentryHand") != null) {
                List<ReceivingBillentryHand> arr = JSON.parseArray(json.getString("billentryHand"), ReceivingBillentryHand.class);
                for (ReceivingBillentryHand hand : arr) {
                    if (hand.getId() == null || hand.getId() == 0) {
                        hand.setReceivingId(receivingNote.getId());
                        hand.setReceiptNo(receivingNote.getReceiptNo());
                        hand.setCreateTime(DateUtils.getNowDate());
                        billentryHandService.save(hand);
                    } else {
                        hand.setUpdateTime(DateUtils.getNowDate());
                        billentryHandService.updateById(hand);
                    }
                }
            }

            if (json.getString("billentryPound") != null) {
                List<ReceivingBillentryPound> arr1 = JSON.parseArray(json.getString("billentryPound"), ReceivingBillentryPound.class);
                for (ReceivingBillentryPound pound : arr1) {
                    pound.setGrossWeight(new BigDecimal(json.getInteger("grossWeight")));
                    pound.setTareWeight(new BigDecimal(json.getInteger("taresWeight")));
                    billentryPoundService.updateById(pound);
                }
            }

            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**
     * 库管员确认收货 -结束
     *
     * @param json
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author JerryLu
     * @date 2024/9/6 11:49
     */
    @PreAuthorize("@ss.hasPermi('system:note:confirm')")
    @PostMapping("/confirm_receiving")
    @Transactional
    public AjaxResult confirmReceiving(@RequestBody JSONObject json) {
        try {
            ReceivingNote receivingNote = new ReceivingNote();
            receivingNote.setId(json.getInteger("id").longValue());
            receivingNote.setReceiptNo(json.getString("receiptNo"));
            receivingNote.setStatus(3);
            receivingNote.setUpdateTime(DateUtils.getNowDate());
            receivingNoteService.updateById(receivingNote);
            ReceivingNote info = receivingNoteService.getById(json.getInteger("id").longValue());

            // 向对应人发送提醒消息
            SysUser user = new SysUser();
            user.setRoleId(2L);
            ArrayList<String> listString = new ArrayList<>();
            List<SysUser> userList = userService.selectAllocatedList(user);
            for (SysUser sysUser : userList) {
                listString.add(sysUser.getPhonenumber());
            }
            listString.add(getLoginUser().getUser().getPhonenumber());
            String[] mobiles = new String[listString.size()];
            listString.toArray(mobiles);

            JSONObject jsonObject = new JSONObject();
            StringBuilder MateriaName = new StringBuilder();
            ReceivingBillentryHand billentryHand = new ReceivingBillentryHand();
            billentryHand.setReceivingId(receivingNote.getId());
            List<ReceivingBillentryHand> handList = billentryHandService.queryList(billentryHand);
            BigDecimal total = BigDecimal.ZERO;
            for (ReceivingBillentryHand s : handList) {
                MateriaName.append(s.getMateriaName()).append(",");
//                if (s.getNetWeight() != null) {
//                    total = total.add(s.getNetWeight());
//                }
            }
            jsonObject.put("type", "收货");
            jsonObject.put("title", "新收货提醒");
            jsonObject.put("number_name", "产品收货总编号");
            jsonObject.put("receiptNo", info.getReceiptNo());
            jsonObject.put("billno", info.getBillno());
            jsonObject.put("name", MateriaName.toString());
            jsonObject.put("weight", total.add(info.getHandWeight()));
            jsonObject.put("fahuo", info.getSupplySupplier());
            jsonObject.put("shouhuo", info.getPurchasingTissue() + " · " + info.getPurchasingDept());
            AjaxResult res = dingDingApi.sendMessage(jsonObject.toString(), mobiles);
            if (res.isSuccess()) {
                return success();
            }
            return error();
        } catch (Exception e) {
            e.printStackTrace();
            return error();
        }
    }
}
